#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8

import sys, os, getopt
import codecs
import fileinput
import re
#from pysqlite2 import dbapi2 as sqlite
import sqlite3

file_db = 'dpedia.db.sqlite'

def hanzi_num(num):
    if num == 1:
        return u'一'
    elif num == 2:
        return u'二'
    elif num == 3:
        return u'三'
    elif num == 4:
        return u'四'
    elif num == 5:
        return u'五'
    elif num == 6:
        return u'六'
    elif num == 7:
        return u'七'
    elif num == 8:
        return u'八'
    elif num == 9:
        return u'九'
    elif num == 10:
        return u'十'

def collect(file):
    global file_db
    error = False
    con = sqlite3.connect(file_db)
    con.row_factory = sqlite3.Row
    cur = con.cursor()

    id = ''
    title = ''
    culture = ''
    region = ''
    age = ''
    resume = ''
    data = ''
    relations = ''
    reference = ''

    current_section = ''
    data_count = 0
    for line in fileinput.input(file, openhook=fileinput.hook_encoded("utf-8")):
        if line.startswith(u'\ufeff'):
            line = line[1:]
            print 'yes, BOM'
            print line
        if line[0] == u'[':
            current_section = line.strip()[1:-1]
            print current_section
            if current_section == u'data':
                data_count = data_count + 1
                data += u'<h5>资料%s</h5>' % (hanzi_num(data_count))
        else:
            if current_section == u'id':
                id = line.strip()
            elif current_section == u'title':
                title = line.strip()
            elif current_section == u'culture':
                culture = line.strip()
            elif current_section == u'region':
                region = line.strip()
            elif current_section == u'age':
                age = line.strip()
            elif current_section == u'resume':
                resume += line
            elif current_section == u'data':
                data += u'<p>' + line + u'</p>\r\n'
            elif current_section == u'relation':
                relations += line
            elif current_section == u'ref':
                reference += line
    else:
        print 'end collecting'

    if not error:
        if data_count == 1:
            data = data[12:]
        #print (id,title,culture,region,age,resume,data,relations,reference)
        cur.execute(u'''insert into pedia (id,title,culture,region,age,resume,data,relations,reference) 
                values('%s','%s','%s','%s','%s','%s','%s','%s','%s')''' 
                % (id,title,culture,region,age,resume,data,relations,reference))
    con.commit()
    cur.close()

def usage():
    print("""
    example: xxx.py -i xx.txt -d xx.db.sqlite

    -h   print this message
    -d   database name
    -i   input file name
    """)

def main(argv):
    file_in = 'input.txt'
    try:
        opts, args = getopt.getopt(argv, 'hd:i:', ['help', 'db=', 'input='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-d', '--db'):
            file_db = arg
        elif opt in ('-i', '--input'):
            file_in = arg
    collect(file_in)

if __name__ == '__main__':
    main(sys.argv[1:])

